package repository

import (
	"context"

	"github.com/example/video_backend/internal/model"
	"gorm.io/gorm"
)

// PlayHistoryRepository 播放历史仓库接口
type PlayHistoryRepository interface {
	CreateOrUpdate(ctx context.Context, history *model.PlayHistory) error
	Delete(ctx context.Context, id uint) error
	ClearUserHistory(ctx context.Context, userID uint) error
	GetUserHistory(ctx context.Context, userID uint, page, pageSize int) ([]*model.PlayHistory, int64, error)
}

// playHistoryRepository 实现PlayHistoryRepository接口
type playHistoryRepository struct {
	db *gorm.DB
}

// NewPlayHistoryRepository 创建播放历史仓库实例
func NewPlayHistoryRepository(db *gorm.DB) PlayHistoryRepository {
	return &playHistoryRepository{db: db}
}

// CreateOrUpdate 创建或更新播放历史
func (r *playHistoryRepository) CreateOrUpdate(ctx context.Context, history *model.PlayHistory) error {
	// 先查询是否已存在记录
	var existing model.PlayHistory
	err := r.db.WithContext(ctx).Where("user_id = ? AND video_id = ?", history.UserID, history.VideoID).First(&existing).Error

	if err != nil {
		// 如果不存在，则创建新记录
		if err == gorm.ErrRecordNotFound {
			return r.db.WithContext(ctx).Create(history).Error
		}
		return err
	}

	// 如果存在，则更新进度和时间
	existing.Progress = history.Progress
	existing.LastPlayedAt = history.LastPlayedAt
	return r.db.WithContext(ctx).Save(&existing).Error
}

// Delete 删除播放历史记录
func (r *playHistoryRepository) Delete(ctx context.Context, id uint) error {
	return r.db.WithContext(ctx).Delete(&model.PlayHistory{}, id).Error
}

// ClearUserHistory 清空用户的播放历史
func (r *playHistoryRepository) ClearUserHistory(ctx context.Context, userID uint) error {
	return r.db.WithContext(ctx).Where("user_id = ?", userID).Delete(&model.PlayHistory{}).Error
}

// GetUserHistory 获取用户的播放历史列表
func (r *playHistoryRepository) GetUserHistory(ctx context.Context, userID uint, page, pageSize int) ([]*model.PlayHistory, int64, error) {
	var histories []*model.PlayHistory
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 构建查询
	query := r.db.WithContext(ctx).Where("user_id = ?", userID)

	// 查询总数
	query.Model(&model.PlayHistory{}).Count(&total)

	// 查询分页数据
	err := query.Offset(offset).Limit(pageSize).Order("last_played_at DESC").Find(&histories).Error
	if err != nil {
		return nil, 0, err
	}

	return histories, total, nil
}
